﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BackOffice.Models;

namespace BackOffice.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {
        private BLL.Concrete.Validations.IFormsAuthenticationService __formsService { get; set; }
        private BLL.Concrete.Validations.IMembershipService __membershipService { get; set; }

        // load
        protected override void Initialize(RequestContext requestContext)
        {
            if (__formsService == null) { __formsService = new BLL.Concrete.Validations.FormsAuthenticationService(); }
            if (__membershipService == null) { __membershipService = new BLL.Concrete.Validations.AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // full
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Home");
            ViewData["__returnUrl"] = Url.Action("Index", "Home");
            return View();
        }
        public ActionResult EndSession(String ReturnUrl)
        {
            ViewData["__session"] = true;
            ViewData["__returnUrl"] = ReturnUrl;
            return View("Index");
        }
        [Authorize]
        public ActionResult LogOff()
        {
            __formsService.SignOut();
            return RedirectToAction("Index", "Account");
        }
        // handlers
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult HandleLogin(BLL.Concrete.Validations.LoginData Data, String ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                if (__membershipService.ValidateUser(Data.UserName, Data.Password))
                {
                    // login
                    String __url = (!String.IsNullOrEmpty(ReturnUrl)) ? ReturnUrl : Url.Action("Index", "Home");
                    __formsService.SignIn(Data.UserName, Data.RememberMe);
                    String __userId = Membership.GetUser(Data.UserName).ProviderUserKey.ToString();
                    if (Request.IsAjaxRequest())
                        return JavaScript("window.top.location.href='" + __url + "';");
                    else
                        return Redirect(Url.Action("Index", "Home"));
                }
                else
                {
                    ViewData.Model = "Nombre de usuario o contraseña invalido";
                    return PartialView("Fail");
                }
            }
            // fail
            ViewData.Model = Data.Error;
            return PartialView("Fail");
        }
    }
}
